//
//  ZYOatuchViewController.swift
//  weibo007
//
//  Created by 陈宗毅 on 15/12/19.
//  Copyright © 2015年 czy. All rights reserved.
//

import UIKit
import SVProgressHUD

class ZYOatuchViewController: UIViewController,UIWebViewDelegate {

    //webView开始加载
    func webViewDidStartLoad(webView:UIWebView){
        SVProgressHUD.showWithStatus("正在加载", maskType: SVProgressHUDMaskType.Black)
    }
    
    //webView加载完毕
    func webViewDidFinishLoad(webView:UIWebView){
        //关闭指示器
        SVProgressHUD.dismiss()
    }
    
    //webView是否要去加载一个网址，返回true去加载，false不去加载
//    func webView(webView:UIWebView,shouldStartLoadWithRequest request:NSURLRequest,navigationType:UIWebViewNavigationType) -> Bool{
//        let url = request.URL?.absoluteString
//
//    }

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let url = request.URL!.absoluteString
        print("url:\(url)")
        //只有点击 取消或授权,才会加载 授权回调地址,其他情况不会加载授权回调地址
        // 不是授权回调地址,直接加载
        
        if !url.hasPrefix(ZYNetworkTool.shareInstance.redirect_uri)
        {
            return true
        }
        // 是授权回调地址,判断是取消还是授权
        // 点击取消: http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        // 点击授权:会以code=开头 http://www.baidu.com/?code=a61c2d7ec7b8c4c9c1962bf4354354c5
        // 获取url中?后面的内容: URL.query就是问号后面的东西
        if let query = request.URL?.query{
            let codeString = "code="
            //判断query 是否以code= 开头
            if query.hasPrefix(codeString){
                // 截取code的值
                // Stirng和NSString之间的转换是不需要添加as? 或 as! 直接使用as
               let queryNS = query as NSString
                let code = queryNS.substringFromIndex(codeString.characters.count)
                print("code = \(code)")
                //调用当前类的loadAccessToken
                loadAccessToken(code)
            }else {
                self.close()
            }
        }else{
            print("query没有值")
        }
        
        return false
    }
    
    func loadAccessToken(code:String){
        ZYNetworkTool.shareInstance.loadAccessToken(code) { (result, error) -> () in
            //error
            if error != nil && result == nil{
                print("error:\(error)")
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                //延迟1秒在关闭
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), {() -> Void in
                    //关闭授权控制器
                    self.close()
                    })
                
                
                return
            }
            
            // 能到下面来没有错误,获取到了AccessToken
            // 保存AccessToken
            //            print("result: \(result)")
            // 字典转模型
            
            let userAccount = ZYUserAccount(dict: result!)
            // 保存对象到沙盒
            userAccount.saveUserAccount()
            
            
//            print("userAccount:\(userAccount)")
            
            //切换到欢迎界面
            AppDelegate.outSwitchRootViewController(false)
//            (UIApplication.sharedApplication().delegate as! AppDelegate).switchRootViewController(false)
//            
            //关闭登陆界面
            self.close()
        }
    }
    
    

    //加载webView
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //加载登陆界面
        let url = ZYNetworkTool.shareInstance.oAuthURL()
        
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
        
        //设置导航栏
        //坐标填充
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        //右边,取消
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        navigationItem.title = "登陆"

    }
    //填充账号密码
    func autoFill(){
        let js = "document.getElementById('userId').value='474385510@qq.com';document.getElementById('passwd').value='yizz131422'"
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    //关闭
    func close(){
        SVProgressHUD.dismiss()
        self.dismissViewControllerAnimated(true, completion: nil)
    }

    
    //懒加载webView
    private lazy var webView = UIWebView()

}
